<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/9/27
 * Time: 17:52
 */
namespace App\Http\Controllers\web;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Module\EntBookCollect;
use App\Module\EntMemberInfo;
use App\Module\BookViewLog;
use App\Module\EntBookInfo;
use App\Module\EntMobileCode;
use App\Module\EntMemberDRP;
use Session;
use DB;
use App\Common\MobileMassege;
use App\Common\Http;

class MemberController extends Controller
{
    public function index()
    {
        $memNumber = $this->return_MemNumber();
        $entMemberInfo = EntMemberInfo::select('MemEndTime', 'YourName', 'WeiXID', 'FilePath1', 'UserID')->where('States', '1')->where('DeleteMark', 1)->where('MemNumber', $memNumber)->first();
        if ($entMemberInfo->WeiXID != '') {
            try {
                $MOpenid = $entMemberInfo->WeiXID;
                $wxUserInfo = $this->getWeiXinUserInfo($MOpenid);
                if (count($wxUserInfo) > 0) {
                    $upentMemberInfo = EntMemberInfo::find($entMemberInfo->UserID);
                    $upentMemberInfo->NickName = $wxUserInfo['nickname'];
                    $upentMemberInfo->FilePath1 = $wxUserInfo['headimgurl'];
                    $upentMemberInfo->save();
                    $islevel = 0;
                    $entMemberDRP = EntMemberDRP::select('DRPLevel')->where('MemNumber', $memNumber)->where('DeleteMark', 1)->first();
                    if (count($entMemberDRP) > 0) {
                        if ($entMemberDRP->DRPLevel > 1) {
                            $islevel = 1;
                        }
                    } else {
                        $islevel = 1;
                    }
                }
            } catch (ModelNotFoundException $e) {
                throw new NotFoundHttpException();
            }
        }
        return view('member.index', ['entMemberInfo' => $entMemberInfo,'islevel'=>$islevel]);
    }

    /**获取微信昵称和头像
     * @param $openid 微信标示
     * @return array|string 返回微信昵称和头像
     */
    protected function getWeiXinUserInfo($openid)
    {
        $wxuserInfo = '';
        $accessToken = 'no';
        if (file_exists('XMLFile.xml')) {
            $xml = simplexml_load_file('XMLFile.xml');
            $endAccessTime = $xml->Access_Time;
            if ($endAccessTime != '') {
                $zero1 = date('Y-m-d H:i:s');
                $zero2 = $endAccessTime;
                if (strtotime($zero1) < strtotime($zero2)) {
                    //未到期
                    $accessToken = $xml->Access_Token;
                } else {
                    //到期
                    $url2 = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . env('WEIXIN_APPID') . '&secret=' . env('WEIXIN_APPSECRET') . '';
                    $http = new Http();
                    $responseText = $http->send($url2);

                    if ($responseText != '') {
                        $jsonAccessToken = json_decode($responseText);

                        if ((array_key_exists('access_token', $jsonAccessToken))) {
                            $accessToken = $jsonAccessToken->access_token;
                            $accessTime = $jsonAccessToken->expires_in;
                            if ($accessToken != '') {
                                $xml->Access_Token = $jsonAccessToken->access_token;//修改节点
                                $xml->Access_Time = date('Y-m-d H:i:s', time() + 7200);
                                $xml->asXML('XMLFile.xml');
                            } else {
                                $accessToken = 'no';
                            }
                        } else {
                            $accessToken = 'no';
                        }
                    } else {
                        $accessToken = 'no';
                    }
                }
            }
        }
        if ($accessToken != 'no') {
            $nickname = '';
            $headimgurl = '';
            $http = new Http();
            $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $accessToken . '&openid=' . $openid . '&lang=zh_CN';
            $responseTextUserInfo = $http->send($url);
            if ($responseTextUserInfo != '') {
                $userInfo = json_decode($responseTextUserInfo);
                if ((array_key_exists('nickname', $userInfo))) {
                    $nickname = $userInfo->nickname;
                }
                if ((array_key_exists('headimgurl', $userInfo))) {
                    $headimgurl = $userInfo->headimgurl;
                }
            }
            $wxuserInfo = ['nickname' => $nickname, 'headimgurl' => $headimgurl];
        }
        return $wxuserInfo;
    }

    public function vip()
    {

        return view('member/vip');
    }

    public function vipsuccess()
    {
        return view('member/vipsuccess');
    }

    public function wait()
    {
        $i = 0;
        $memNumber = $this->return_MemNumber();
        if (count($memNumber) > 0) {
            $entMemberDRP = EntMemberDRP::select('DRPID', 'DRPLevel', 'ParentID')->where('MemNumber', $memNumber)->first();
            if (count($entMemberDRP) > 0) {
                if ($entMemberDRP->DRPLevel == 1) {
                    //合伙人图片
                    $i = $memNumber;
                } else {
                    if ($entMemberDRP->ParentID > 0) {
                        //上级合伙人
                        $entMemberDRPTwo = EntMemberDRP::select('DRPID', 'DRPLevel', 'ParentID', 'MemNumber')->where('DRPID', $entMemberDRP->ParentID)->first();
                        if (count($entMemberDRPTwo) > 0) {
                            $i = $entMemberDRPTwo->MemNumber;
                        } else {
                            $i = 0;
                        }
                    } else {
                        //默认
                        $i = 0;
                    }
                }
            } else {
                //默认
                $i = 0;
            }
        }
        return view('member.wait', ['i' => $i]);
    }

    //绑定老会员
    public function vipmobile(Request $request)
    {

        $result = '';
        try {
            if ($request->ajax()) {
                $mobile = $request->json('mobile');
                $entMemberInfoCount = EntMemberInfo::select('MemNumber', 'WeiXID')->where('States', '1')->where('DeleteMark', 1)->where('UserName', $mobile)->first();
                if (count($entMemberInfoCount) == 0) {
                    $result = '2';
                } else {
                    $MOpenid = Session::get('OPENID');
                    if ($MOpenid != '') {
                        if ($entMemberInfoCount->WeiXID != '') {
                            $result = '5';
                        } else {
                            $entMemberInfoTwo = EntMemberInfo::select('MemNumber')->where('States', '1')->where('WeiXID', $MOpenid)->first();
                            if (count($entMemberInfoTwo) == 0) {
                                $loginKey = md5(date('YmdHis', time()));
                                $upEntMemberInfo = EntMemberInfo::where('MemNumber', $entMemberInfoCount->MemNumber)->where('UserName', $mobile)->update(['WeiXID' => $MOpenid, 'LoginKey' => $loginKey]);
                                if (count($upEntMemberInfo) == 1) {
                                    Session::put('MName', $mobile);
                                    Session::put('MKey', $loginKey);
                                    $result = '1';
                                } else {
                                    $result = '4';
                                }
                            } else {
                                $result = '3';
                            }
                        }
                    }
                }
            } else {
                $result = '4';
            }
        } catch (Exception $e) {
            $result = '4';
        }
        return $result;
    }

    // 验证手机验证码
    public function addVipMobCode(Request $request)
    {
        $usermobile = $request->json('mobile');
        if(empty($usermobile)){
            return 4;
        }

        $entMobileCodeTime = EntMobileCode::select('EndTime', 'ID')->where('Mobile', $usermobile)
            ->where('States', 1)
            ->orderBy('AddDate', 'desc')
            ->first();

        if (count($entMobileCodeTime) > 0) {
            $nowtime = date('Y-m-d h:i:s', time());
            $endtime = $entMobileCodeTime->EndTime;
            if (strtotime($nowtime) < strtotime($endtime)) { // 时间没有到
                return 2;
            }
        }

        $messageModel = new MobileMassege();
        $messageModel->mobile = $usermobile;
        $res = $messageModel->send_valid_code();
        if($res){
            return 3;
        }else{
            return 4;
        }
    }

    public function vipcheckMobCode(Request $request)
    {
        $usermobcode = $request->json('mobcode');
        $usermobile = $request->json('mobile');

        $entMemberInfo = EntMemberInfo::select('UserID', 'States')->where('UserName', $usermobile)
            ->where('DeleteMark', 1)
            ->first();

        if (!count($entMemberInfo) > 0) {
            return 1;   //注册页面
        }
        if ($entMemberInfo->States != 1) {
            return 5;   //支付页面
        }

        $messageModel = new MobileMassege();
        $res = $messageModel->check_valid_code($usermobile,$usermobcode);
        if($res){
            $messageModel->delete_code($usermobile,$usermobcode);
            return 3;
        }else{
            return 2;    // 您输入的手机验证码不正确
        }
    }

    //随机数字
    protected function RandStr($n)
    {
        $s = '';
        $str = "123456789"; // 输出字符集
        $len = strlen($str) - 1;
        for ($i = 0; $i < $n; $i++) {
            $s .= $str[rand(0, $len)];
        }
        return $s;
    }



    public function bookmend()
    {
        $memNumber = $this->return_MemNumber();
        $entBookViewLog = DB::table('VW_WEB_BookSumUps')->select('BookID', 'FilePath1', 'BookTitle', 'StartTime', 'EndTime', 'BookReview1', 'BookReview2', 'BookReview3', 'BookReview4', 'AddDate')->where('MemNumber', $memNumber)->orderBy('AddDate', 'desc')->get();
        return view('member.bookmend', ['entBookViewLog' => $entBookViewLog]);
    }

    public function bookcollect()
    {
        $memNumber = $this->return_MemNumber();
        $entBookCollect = EntBookCollect::select('ColID', 'BookID', 'FilePath1')->where('MemNumber', $memNumber)->orderBy('AddDate', 'desc')->get();
        return view('member.bookcollect', ['entBookCollect' => $entBookCollect]);
    }

    public function booklookat()
    {
        $memNumber = $this->return_MemNumber();
        $entBookViewLog = DB::table('VW_WEB_BookViewLogs')->select('BookID', 'FilePath1', 'BookTitle', 'StartTime', 'EndTime', 'AddDate')->where('MemNumber', $memNumber)->get();
        return view('member.booklookat', ['entBookViewLog' => $entBookViewLog]);
    }

    protected function return_MemNumber()
    {
        $i = 0;
        try {
            $MName = Session::get('MName');
            $MKey = Session::get('MKey');
            if ($MName != '' && $MKey != '') {
                $entMemberInfo = EntMemberInfo::select('MemNumber')->where('UserName', $MName)->where('LoginKey', $MKey)
                    ->where('DeleteMark', '1')
                    ->where('States', '1')
                    ->first();
                if (count($entMemberInfo) > 0) {
                    $i = $entMemberInfo->MemNumber;
                }
            }
        } catch (ModelNotFoundException $e) {
            $i = 0;
        }
        return $i;
    }

}